<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>发表评论 - 内容评级平台</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        :root {
            --primary: #4361ee;
            --secondary: #3f37c9;
            --accent: #4cc9f0;
            --dark: #1d3557;
            --darker: #0d1b2a;
            --light: #f8f9fa;
            --gray: #8d99ae;
            --success: #4caf50;
            --warning: #ff9800;
            --danger: #f44336;
            --card-bg: rgba(29, 53, 87, 0.8);
            --transition: all 0.3s ease;
        }

        body {
            background: linear-gradient(135deg, var(--darker) 0%, var(--dark) 100%);
            color: var(--light);
            min-height: 100vh;
            background-attachment: fixed;
            line-height: 1.6;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            margin: 0;
            padding: 0;
        }

        .review-container {
            max-width: 800px;
            margin: 2rem auto;
            padding: 2rem;
            background: var(--card-bg);
            border-radius: 15px;
            box-shadow: 0 10px 20px rgba(0,0,0,0.2);
        }

        .review-header {
            margin-bottom: 2rem;
            text-align: center;
        }

        .review-title {
            font-size: 1.8rem;
            color: var(--accent);
            margin-bottom: 0.5rem;
        }

        .review-subtitle {
            color: var(--gray);
            font-size: 1.1rem;
        }

        .content-preview {
            display: flex;
            align-items: center;
            gap: 1.5rem;
            margin-bottom: 2rem;
            padding-bottom: 1.5rem;
            border-bottom: 1px solid rgba(255,255,255,0.1);
        }

        .content-poster {
            width: 120px;
            height: 180px;
            object-fit: cover;
            border-radius: 8px;
            transition: var(--transition);
            opacity: 0;
            transform: translateY(10px);
        }

        .content-poster.loaded {
            opacity: 1;
            transform: translateY(0);
        }

        .content-poster.error {
            opacity: 1;
            transform: translateY(0);
            background: var(--dark);
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .content-info h3 {
            font-size: 1.3rem;
            margin-bottom: 0.5rem;
        }

        .content-meta {
            color: var(--gray);
            font-size: 0.9rem;
        }

        .rating-section {
            margin-bottom: 2rem;
        }

        .rating-title {
            font-size: 1.2rem;
            margin-bottom: 1rem;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }

        .rating-stars {
            display: flex;
            gap: 0.5rem;
            margin-bottom: 1rem;
        }

        .star {
            font-size: 2rem;
            color: var(--gray);
            cursor: pointer;
            transition: var(--transition);
        }

        .star:hover, .star.active {
            color: var(--warning);
            transform: scale(1.1);
        }

        .rating-description {
            color: var(--gray);
            font-size: 0.9rem;
            margin-top: 0.5rem;
            text-align: center;
        }

        .form-group {
            margin-bottom: 1.5rem;
        }

        .form-label {
            display: block;
            margin-bottom: 0.5rem;
            font-weight: 500;
        }

        .form-control {
            width: 100%;
            padding: 0.8rem;
            border-radius: 8px;
            border: 1px solid rgba(255,255,255,0.2);
            background: rgba(255,255,255,0.1);
            color: var(--light);
            font-family: inherit;
            font-size: 1rem;
            transition: var(--transition);
        }

        .form-control:focus {
            outline: none;
            border-color: var(--accent);
            box-shadow: 0 0 0 2px rgba(76, 201, 240, 0.3);
        }

        textarea.form-control {
            min-height: 150px;
            resize: vertical;
        }

        .form-actions {
            display: flex;
            justify-content: flex-end;
            gap: 1rem;
        }

        .btn {
            padding: 0.8rem 1.5rem;
            border-radius: 30px;
            font-weight: 500;
            font-size: 1rem;
            cursor: pointer;
            transition: var(--transition);
            display: inline-flex;
            align-items: center;
            gap: 0.5rem;
        }

        .btn-primary {
            background: var(--primary);
            color: white;
            border: none;
        }

        .btn-primary:hover {
            background: var(--secondary);
            transform: translateY(-2px);
            box-shadow: 0 4px 15px rgba(67, 97, 238, 0.4);
        }

        .btn-outline {
            background: transparent;
            color: var(--primary);
            border: 2px solid var(--primary);
        }

        .btn-outline:hover {
            background: rgba(67, 97, 238, 0.1);
        }

        .error-message {
            color: var(--danger);
            font-size: 0.9rem;
            margin-top: 0.5rem;
            display: none;
        }

        .has-error .error-message {
            display: block;
        }

        .has-error .form-control {
            border-color: var(--danger);
        }

        .review-message {
            position: fixed;
            bottom: 20px;
            right: 20px;
            background: var(--success);
            color: white;
            padding: 12px 24px;
            border-radius: 5px;
            z-index: 1000;
            display: flex;
            align-items: center;
            gap: 0.8rem;
            box-shadow: 0 4px 12px rgba(0,0,0,0.15);
            animation: slideIn 0.3s ease;
        }

        .review-error {
            background: var(--danger);
        }

        @keyframes slideIn {
            from { transform: translateX(100%); opacity: 0; }
            to { transform: translateX(0); opacity: 1; }
        }

        /* 响应式设计 */
        @media (max-width: 768px) {
            .content-preview {
                flex-direction: column;
                text-align: center;
            }

            .review-container {
                padding: 1.5rem;
                margin: 1rem;
            }

            .review-title {
                font-size: 1.5rem;
            }
        }
    </style>
</head>
<body>
<%@ include file="navbar.jsp" %>

<div class="review-container">
    <div class="review-header">
        <h1 class="review-title">
            <c:choose>
                <c:when test="${content.type == 'movie'}">发表影评</c:when>
                <c:when test="${content.type == 'book'}">发表书评</c:when>
                <c:when test="${content.type == 'music'}">发表乐评</c:when>
                <c:otherwise>发表评论</c:otherwise>
            </c:choose>
        </h1>
        <p class="review-subtitle">分享您对这部作品的看法</p>
    </div>

    <div class="content-preview">
        <c:choose>
            <c:when test="${not empty content.imageUrl}">
                <img src="${content.imageUrl}" alt="${content.title}" class="content-poster"
                     onerror="handleImageError(this)"
                     onload="handleImageLoad(this)">
            </c:when>
            <c:otherwise>
                <div class="content-poster error">
                    <i class="fas fa-image" style="font-size: 2rem; color: var(--gray);"></i>
                </div>
            </c:otherwise>
        </c:choose>
        <div class="content-info">
            <h3>${content.title}</h3>
            <div class="content-meta">
                <c:choose>
                    <c:when test="${content.type == 'movie'}">
                        导演: ${content.directorOrAuthor} | 上映: ${content.releaseOrPublishDate}
                    </c:when>
                    <c:when test="${content.type == 'book'}">
                        作者: ${content.directorOrAuthor} | 出版: ${content.releaseOrPublishDate}
                    </c:when>
                    <c:when test="${content.type == 'music'}">
                        艺术家: ${content.directorOrAuthor} | 发行: ${content.releaseOrPublishDate}
                    </c:when>
                </c:choose>
            </div>
        </div>
    </div>

    <form id="reviewForm" action="${pageContext.request.contextPath}/add-comment" method="post">
        <input type="hidden" name="contentId" id="contentIdField" value="${param.contentId}">
        <input type="hidden" name="contentType" id="contentTypeField" value="${param.type}">
        <c:if test="${not empty userReview}">
            <input type="hidden" name="commentId" value="${userReview.id}">
        </c:if>

        <div class="rating-section">
            <h3 class="rating-title">
                <i class="fas fa-star"></i>
                您的评分
            </h3>
            <div class="rating-stars">
                <c:forEach begin="1" end="5" var="i">
                    <i class="star fas fa-star ${not empty userReview && i <= userReview.rating ? 'active' : ''}"
                       data-rating="${i}"
                       onclick="setRating(${i})"></i>
                </c:forEach>
            </div>
            <p class="rating-description" id="ratingDescription">
                <c:choose>
                    <c:when test="${not empty userReview}">
                        您之前评分为 ${userReview.rating} 星
                    </c:when>
                    <c:otherwise>
                        请选择1-5星评分
                    </c:otherwise>
                </c:choose>
            </p>
            <input type="hidden" id="userRating" name="rating" value="${not empty userReview ? userReview.rating : ''}">
        </div>

        <div class="form-group">
            <label for="reviewContent" class="form-label">
                <i class="fas fa-pen"></i>
                评论内容
            </label>
            <textarea id="reviewContent" name="content" class="form-control"
                      placeholder="写下您的详细评论..." required>${not empty userReview ? userReview.content : ''}</textarea>
            <div class="error-message" id="contentError">评论内容不能为空</div>
        </div>

        <div class="form-actions">
            <button type="button" class="btn btn-outline" onclick="window.history.back()">
                <i class="fas fa-arrow-left"></i> 返回
            </button>
            <button type="submit" class="btn btn-primary">
                <i class="fas fa-paper-plane"></i> ${not empty userReview ? '更新评论' : '提交评论'}
            </button>
        </div>
    </form>
</div>

<%@ include file="footer.jsp" %>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
    // 页面加载完成后执行
    $(document).ready(function() {
        initPage();
        $('#reviewForm').submit(function(e) {
            e.preventDefault();
            handleFormSubmit();
        });
    });

    // 初始化页面
    function initPage() {
        const contentId = $('#contentIdField').val();
        const contentType = $('#contentTypeField').val();

        if (!contentId || !contentType) {
            console.error('缺少必要参数:', {contentId, contentType});
            showMessage('页面参数错误，请从内容详情页重新进入', 'error');
            setTimeout(() => {
                window.location.href = '${pageContext.request.contextPath}/index.jsp';
            }, 2000);
            return;
        }

        if (${not empty userReview}) {
            setRating(${userReview.rating});
        }
    }

    // 设置评分
    function setRating(rating) {
        $('.star').each(function() {
            const starRating = parseInt($(this).data('rating'));
            $(this).toggleClass('active', starRating <= rating);
        });
        $('#userRating').val(rating);

        const descriptions = ["很差，不推荐", "较差，有待改进", "一般，中规中矩", "很好，推荐观看", "非常棒，强烈推荐"];
        $('#ratingDescription')
            .text(descriptions[rating - 1])
            .css('color', 'var(--light)');
    }

    // 处理表单提交
    function handleFormSubmit() {
        if (!validateForm()) {
            return;
        }

        const form = $('#reviewForm');
        const submitBtn = form.find('button[type="submit"]');
        const originalHtml = submitBtn.html();

        submitBtn.html('<i class="fas fa-spinner fa-spin"></i> 提交中...');
        submitBtn.prop('disabled', true);

        const formData = prepareFormData(form);

        if (!formData.contentId || !formData.contentType) {
            showMessage('内容信息不完整，请刷新页面重试', 'error');
            resetSubmitButton(submitBtn, originalHtml);
            return;
        }

        submitReview(form, formData, submitBtn, originalHtml);
    }

    // 验证表单
    function validateForm() {
        let isValid = true;

        const rating = $('#userRating').val();
        if (!rating || rating < 1 || rating > 5) {
            isValid = false;
            $('#ratingDescription')
                .css('color', 'var(--danger)')
                .text('请选择评分');
        }

        const content = $('#reviewContent').val().trim();
        if (!content) {
            isValid = false;
            $('#reviewContent').addClass('has-error');
            $('#contentError').show();
        } else {
            $('#reviewContent').removeClass('has-error');
            $('#contentError').hide();
        }

        return isValid;
    }

    // 准备表单数据
    function prepareFormData(form) {
        const formData = {
            contentId: $('#contentIdField').val(),
            contentType: $('#contentTypeField').val(),
            rating: $('#userRating').val(),
            content: $('#reviewContent').val().trim()
        };

        const commentId = form.find('[name="commentId"]').val();
        if (commentId) {
            formData.commentId = commentId;
        }

        return formData;
    }

    // 提交评论
    function submitReview(form, formData, submitBtn, originalHtml) {
        $.ajax({
            url: form.attr('action'),
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(formData),
            success: function(response) {
                handleSubmitResponse(response, formData);
            },
            error: function(xhr, status, error) {
                console.error('AJAX请求失败:', status, error);
                showMessage('网络错误，请稍后再试', 'error');
            },
            complete: function() {
                resetSubmitButton(submitBtn, originalHtml);
            }
        });
    }

    // 处理提交响应
    function handleSubmitResponse(response, formData) {
        try {
            const result = typeof response === 'string' ? JSON.parse(response) : response;

            if (result.success) {
                showMessage(result.message || '评论提交成功', 'success');
                setTimeout(() => {
                    window.location.href = '${pageContext.request.contextPath}/content/detail?id=' +
                        formData.contentId + '&type=' + formData.contentType;
                }, 1500);
            } else {
                handleSubmitError(result);
            }
        } catch (e) {
            console.error('解析响应失败:', e);
            showMessage('处理响应失败: ' + (response.message || response), 'error');
        }
    }

    // 重置提交按钮状态
    function resetSubmitButton(submitBtn, originalHtml) {
        submitBtn.html(originalHtml);
        submitBtn.prop('disabled', false);
    }

    // 显示消息
    function showMessage(message, type) {
        $('.review-message').remove();
        const messageDiv = $('<div class="review-message"></div>')
            .addClass(type === 'error' ? 'review-error' : 'review-success')
            .html('<i class="fas ' + (type === 'success' ? 'fa-check-circle' : 'fa-exclamation-circle') + '"></i>' +
                '<span>' + message + '</span>')
            .appendTo('body')
            .hide()
            .fadeIn(300);

        setTimeout(function() {
            messageDiv.fadeOut(500, function() {
                $(this).remove();
            });
        }, 3000);
    }

    // 错误处理
    function handleSubmitError(result) {
        let errorMsg = result.message || '提交失败';

        if (result.code === 400) {
            if (errorMsg.includes('评分')) {
                $('#ratingDescription')
                    .css('color', 'var(--danger)')
                    .text(errorMsg);
            } else if (errorMsg.includes('内容')) {
                $('#reviewContent').addClass('has-error');
                $('#contentError').text(errorMsg).show();
            } else {
                showMessage('请检查填写的信息是否正确', 'error');
            }
        } else {
            showMessage(errorMsg, 'error');
        }
    }

    // 图片加载处理
    function handleImageLoad(img) {
        img.classList.add('loaded');
    }

    function handleImageError(img) {
        img.classList.add('error');
        img.src = 'https://picsum.photos/120/180?random=' + Math.floor(Math.random() * 1000) + '&text=图片加载失败';
        img.alt = '图片加载失败';
        img.onload = null;
    }

    // 确保函数全局可用
    window.handleImageLoad = handleImageLoad;
    window.handleImageError = handleImageError;
</script>
</body>
</html>